package com.cn.wanxi.controller;

import com.cn.wanxi.entity.ImgEntity;
import com.cn.wanxi.entity.ProductEntity;
import com.cn.wanxi.entity.ResultEntity;
import com.cn.wanxi.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/back/product")
public class ProductController {
    @Autowired
    private IProductService productService;

    @RequestMapping("/add")
    protected ResultEntity add(ProductEntity productEntity) {
        return productService.add(productEntity);
    }

    @RequestMapping("/del")
    protected ResultEntity delete(ProductEntity productEntity) {
        return productService.delete(productEntity);
    }

    @RequestMapping("/get")
    protected ResultEntity findAll(ProductEntity productEntity) {
        return ResultEntity.success(productService.findAll(productEntity));
    }

    @RequestMapping("/id")
    protected ResultEntity findById(ProductEntity productEntity) {
        return productService.findById(productEntity);
    }

    @RequestMapping("/post")
    protected ResultEntity update(ProductEntity productEntity) {
        return productService.update(productEntity);
    }

    @RequestMapping("/count")
    protected ResultEntity getCount(ProductEntity productEntity) {
        int result = productService.getCount(productEntity);
        ResultEntity resultModel;
        if (result > 0) {
            resultModel = ResultEntity.success(result);
        } else {
            resultModel = ResultEntity.failed("查找总数失败");
        }
        return resultModel;
    }

    @RequestMapping("/pic")
    protected ResultEntity uploadImg(@RequestParam("file") MultipartFile multipartFile) {
        String logoName = multipartFile.getOriginalFilename();
        String fileName = UUID.randomUUID() + "-----" + logoName;

        String path = "D:\\JavaProject\\step-6\\webapp\\img\\productImg/";
        File file = new File(path + fileName);
        try {
            multipartFile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        ResultEntity<ImgEntity> success = ResultEntity.success(new ImgEntity("/webapp/img/productImg/" + fileName));
        success.setCode(0);
        return success;
    }

    @RequestMapping("/previous")
    protected ResultEntity findPrevious(ProductEntity productEntity) {
        return productService.findPrevious(productEntity);
    }

    @RequestMapping("/next")
    protected ResultEntity findNext(ProductEntity productEntity) {
        return productService.findNext(productEntity);
    }
}
